package Array;

import java.util.Arrays;

/**
 * 26. Remove Duplicates from Sorted Array（删除排序数组中的重复项）
 * https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
 *
 * Given a sorted array nums, remove the duplicates(重复) in-place(原地)
 * such that each element appear only once and return the new length.
 *
 * Do not allocate(分配) extra(额外) space for another array,
 * you must do this by modifying(修改) the input array in-place with O(1) extra memory.
 *
 * Example 1:
 *
 * Given nums = [1,1,2],
 *
 * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
 *
 * It doesn't matter what you leave beyond(超过) the returned length.
 *
 * Example 2:
 *
 * Given nums = [0,0,1,1,1,2,2,3,3,4],
 *
 * Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
 *
 * It doesn't matter what values are set beyond(超过) the returned length.
 *
 * Clarification(说明):
 *
 * Confused why the returned value is an integer but your answer is an array?
 *
 * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
 *
 * Internally you can think of this:
 *
 * // nums is passed in by reference. (i.e., without making a copy)
 * int len = removeDuplicates(nums);
 *
 * // any modification to nums in your function would be known by the caller.
 * // using the length returned by your function, it prints the first len elements.
 * for (int i = 0; i < len; i++) {
 *     print(nums[i]);
 * }
 */
public class E_26_删除排序数组中的重复项 {
    /**
     * 使用快慢指针解决
     * 开始时这两个指针指向第一个数字
     * 如果两个指针数字相同，则快指针+1
     * 如果两个指针数字不同，则快慢指针同时+1
     * 当快指针走完整个数组后，慢指针当前的坐标加1就是数组中不同数字的个数
     * @return
     */
    public static int removeDuplicates(int[] nums) {
        int slow = 0, fast = 0;
        int length = nums.length;
        for (; fast < length; fast++) {
            if (nums[fast] != nums[slow]) {
                slow += 1;
                nums[slow] = nums[fast];
            }
        }
        System.out.println(Arrays.toString(nums));
        return slow+1;
    }

    public static void main(String[] args) {
        System.out.println(removeDuplicates(new int[]{1, 1, 2}));
        System.out.println(removeDuplicates(new int[]{0,0,1,1,1,2,2,3,3,4}));
    }
}
